package gold.digger;

import gold.utils.InputUtil;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LC2232 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public String minimizeResult(String expression) {
            int idx = expression.indexOf("+"), i = idx - 1, j = idx + 1, iMin = 0, jMin = expression.length() - 1;    //  (i+j)
            int val = Integer.parseInt(expression.substring(0, idx)) + Integer.parseInt(expression.substring(idx + 1, expression.length()));
            while (i >= 0) {
                int leftMulti = i == 0 ? 1 : Integer.parseInt(expression.substring(0, i));
                j = idx + 1;
                while (j < expression.length()) {
                    int middle = Integer.parseInt(expression.substring(i, idx)) + Integer.parseInt(expression.substring(idx + 1, j + 1));
                    int rightMulti = j == expression.length() - 1 ? 1 : Integer.parseInt(expression.substring(j + 1, expression.length()));
                    int currentVal = leftMulti * middle * rightMulti;
                    if (currentVal < val) {
                        iMin = i;
                        jMin = j;
                        val = currentVal;
                    }
                    j++;
                }

                i--;
            }

            return expression.substring(0, iMin) + "(" + expression.substring(iMin, jMin + 1) + ")" + expression.substring(jMin + 1, expression.length());
        }
    }

    public void run() {
        System.out.println(new Solution().minimizeResult("247+38"));
        System.out.println(new Solution().minimizeResult("12+34"));
        System.out.println(new Solution().minimizeResult("999+999"));
    }

    public static void main(String[] args) throws Exception {
        LC2232 an = new LC2232();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
